/**
 * 自定义 request 网络请求工具,基于axios
 * @author LiQingSong
 */
import axios, { AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
import { notification, message } from "ant-design-vue";
import { API_ROOT_NEW, CLIENT_SECRET, CLIENTID } from '@/config/env';
import { removeToken } from '@/utils/localToken';
import { clearStore, getStore } from "./store";
import md5 from "md5";
import { getUrlParams } from "./common";
import qs from "qs";
import store from "@/store";

export interface ResponseData {
  code: number;
  data?: any;
  msg?: string;
  accessToken?: string;
}

const customCodeMessage: { [key: number]: string } = {
  10002: '当前用户登入信息已失效，请重新登入再操作', // 未登陆
};

const serverCodeMessage: { [key: number]: string } = {
  200: '服务器成功返回请求的数据',
  400: 'Bad Request',
  401: 'Unauthorized',
  403: 'Forbidden',
  404: 'Not Found',
  500: '服务器发生错误，请检查服务器(Internal Server Error)',
  502: '网关错误(Bad Gateway)',
  503: '服务不可用，服务器暂时过载或维护(Service Unavailable)',
  504: '网关超时(Gateway Timeout)',
};

/**
 * 异常处理程序
 */
const errorHandler = (error: any) => {
  const { response } = error;
  if (error.message === "CancelToken") {
    // 取消请求 Token
    // eslint-disable-next-line no-console
  } else if (response && response.status) {
    const errorText = serverCodeMessage[response.status] || response.statusText;
    const { status, request } = response;
    if (error.response.status === 401) {
      clearStore();
      removeToken();
      store.commit("user/saveCurrentUser", {});
      if (!(window as any)?.__POWERED_BY_QIANKUN__) {
        // router.replace('/user/login');
        window.location.href = `${process.env.VUE_APP_PLUBLIC_PATH}#/user/login?redirect=/home/workplace`;
      } else {
        window.location.href = `/#/user/login?redirect=/home/workplace`;
        //跳转到主应用登陆页面
      }
    } else if (error.response.status === 400) {
      message.error(error.response.data ? error.response.data.msg : errorText)
    } else {
        message.error(error.response.data ? error.response.data.msg : errorText)
    }

  } else if (!response) {
    notification.error({
      description: "您的网络发生异常，无法连接服务器",
      message: "网络异常",
    });
  }
}



/**
 * 配置request请求时的默认参数
 */
const request = axios.create({
  baseURL: API_ROOT_NEW,//process.env.VUE_APP_API_ROOT,
  timeout: 0 // 请求超时时间,5000(单位毫秒) / 0 不做限制
});


//正式，灰度，测试接口地址区分。
const PAY_APP_KEY: any = process.env.VUE_APP_PAY_APP_KEY;
const whiteList = ["/user/login"];


request.interceptors.request.use(
  (req: any) => {
    // 下面这些是非支付那些的接口
    if (!req.params) {
      req.params = {};
    }
    req.params.timestamp = new Date().getTime();
    req.params.platform = 50;

    for (const key in req.params) {
      if (
        req.params[key] === null ||
        req.params[key] === undefined ||
        req.params[key] === "" ||
        JSON.stringify(req.params[key]) == "{}"
      ) {
        delete req.params[key];
      }
    }

    for (const key in req.data) {
      if (
        req.data[key] === null ||
        req.data[key] === undefined ||
        req.data[key] === "" ||
        JSON.stringify(req.data[key]) == "{}"
      ) {
        delete req.data[key];
      }
    }

    const clientId = CLIENTID;
    const clientSecret = CLIENT_SECRET;
    let signCode;
    if (req.params && typeof req.params === "object" && req.params["cType"]) {
      delete req.params.cType;
      const paramsStr = qs.stringify(req.params);
      signCode = md5(`${paramsStr}+${clientSecret}`);
    } else if (
      req.data &&
      typeof req.data === "object" &&
      req.data["isSignatur"]
    ) {
      const a: any = {};
      delete req.data.isSignatur;
      const obj: any = Object.assign(req.params, req.data);
      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          a[key] = typeof obj[key] === "object"
            ? JSON.stringify(obj[key])
            : obj[key];
        }
      }
      const paramsStr = `${getUrlParams(a)}`;
      req.data = "";

      signCode = md5(paramsStr);
    } else if (req.method === "get" || req.method === "delete") {
      const a: any = {};
      for (const key in req.params) {
        if (req.params.hasOwnProperty(key)) {
          a[key] =
            typeof req.params[key] === "object"
              ? JSON.stringify(req.params[key])
              : req.params[key];
        }
      }
      const paramsStr = `${getUrlParams(a)}`;
      signCode = md5(paramsStr);
    } else {
      const data = req.data;
      if (data.clientSecret) {
        data.clientSecret = md5(data.clientSecret);
        const paramsStr = `${getUrlParams(req.params)}+${JSON.stringify({
          ...data,
        })}+${clientSecret}`;
        signCode = md5(paramsStr);
      } else {
        const paramsStr = `${getUrlParams(req.params)}+${JSON.stringify(
          data
        )}`;
        signCode = md5(paramsStr);
      }
    }

    req.headers["signCode"] = signCode;
    req.headers["clientId"] = clientId;
    if (!whiteList.find((item) => req.url?.indexOf(item) > -1)) {
      const token = getStore("newToken");
      req.headers['Authorization'] = `Bearer ${token}`;
    }
    if (req.params["export"]) {
      //请求导出文件时设置
      req.responseType = "blob";
    } else {
      req.responseType = "json";
    }
    return req;

  },
  (error) => {
    Promise.reject(error);
  }
);
/**
 * 请求后
 * 响应拦截器
 */

request.interceptors.response.use(
  (response) => {
    if (response.request.responseType == "blob") {
      return response;
    } else if (response.data.code !== 1) {
      message.error(response.data.msg || "网络异常～");
      return response
    } else {
      return response;
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);


export default function (config: AxiosRequestConfig): AxiosPromise<any> {
  return request(config).then((response: AxiosResponse) => response.request.responseType == "blob" ? response : response.data)
    .catch((error) => errorHandler(error));
}
